import React from 'react'

import { FORMS_CONFIG_MAP } from "./form"
import style from "./index.less"
import { ImgBox } from "../../commons/image-box"
import { MyIcon } from "../../my-icon"

class NormalForm extends React.Component {

    constructor(){
        super()
        this.state = {
            draging: false,
            dragingRect: {
                top: 0,
                left: 0,
                width: 0,
                height: 0,
            }
        }

        this.formRef = React.createRef()
        this.resizeRef = React.createRef()
        this.deleteRef = React.createRef()
    }

    componentDidMount(){
        this.formRef.current.addEventListener("touchstart", this.onTouchStart, {passive: false})

        if(this.resizeRef.current){
            this.resizeRef.current.addEventListener("touchstart", this.onResizeHandleTouchStart, {passive: false})
        }
        if(this.deleteRef.current){
            this.deleteRef.current.addEventListener("touchstart", this.onClickEditorCancel, {passive: false})
        }
    }

    componentDidUpdate(){
        if(this.resizeRef.current){
            this.resizeRef.current.addEventListener("touchstart", this.onResizeHandleTouchStart, {passive: false})
        }
        if(this.deleteRef.current){
            this.deleteRef.current.addEventListener("touchstart", this.onClickEditorCancel, {passive: false})
        }
    }


  onTouchStart = (e) => {
        e.stopPropagation()
        e.preventDefault()

        if(this.state.draging) return

        let isActive = this.props.isActive
        this.props.onActive && this.props.onActive()


        let el = this.formRef.current
        if(!el) return
        let rect = el.getBoundingClientRect()
        let startTouch = e.targetTouches[0]
        if(!startTouch) return

        const startX = startTouch.clientX
        const startY = startTouch.clientY
        const startTop = rect.top
        const startLeft = rect.left

        let moved = false

        const onTouchMove = e => {
            e.stopPropagation()
            e.preventDefault()
            let targetTouch = e.targetTouches[0]
            if(!targetTouch) return
            const dX = targetTouch.clientX - startX
            const dY = targetTouch.clientY - startY

            if(Math.abs(dX) >= 3 && Math.abs(dY) >= 3){
                moved = true
            }

            el.style.top = startTop + dY + "px"
            el.style.left = startLeft + dX + "px"
        }

        const onTouchEnd = e => {
            e.stopPropagation()
            e.preventDefault()
          this.forceUpdate()
            if(!moved){
                if(isActive){
                    this.props.onSign && this.props.onSign()
                }
            } else {
                this.props.onUpdateFormPostion && this.props.onUpdateFormPostion(this.props.formData, el.getBoundingClientRect())
            }

            this.setState({
                draging: false,
            })
          window.removeEventListener("touchmove", onTouchMove, { passive: false })
          window.removeEventListener("touchend", onTouchEnd, { passive: false })
        }

    window.addEventListener("touchmove", onTouchMove, { passive: false })
    window.addEventListener("touchend", onTouchEnd, { passive: false })

        this.setState({
            draging: true,
            dragingRect: {
                top: rect.top,
                left: rect.left,
                width: rect.width,
                height: rect.height,
            }
        })
    }
    onResizeHandleTouchStart = (e) => {
        e.preventDefault()
        e.stopPropagation()

        let el = this.formRef.current
        if(!el) return
        let pageContainer = this.formRef.current.parentElement
        if(!pageContainer) return

        let startTouch = e.targetTouches[0]
        if(!startTouch) return

        let scale = this.props.scale || 1
        let formConfig = FORMS_CONFIG_MAP.get(this.props.formData.type)
        let minWidth = formConfig.minSize.width * scale
        let minHeight = formConfig.minSize.height * scale

        let formData = this.props.formData

        let pageContainerRect = pageContainer.getBoundingClientRect()
        const pageContainerWidth = pageContainerRect.width
        const pageContainerHeight = pageContainerRect.height

        const startX = startTouch.clientX
        const startY = startTouch.clientY
        const startLeft = formData.position.left * scale
        const startTop = formData.position.top * scale
        const startWidth = formData.position.width * scale
        const startHeight = formData.position.height * scale

        const onTouchMove = e => {
            e.stopPropagation()
            e.preventDefault()
            let targetTouch = e.targetTouches[0]
            if(!targetTouch) return

            const endX = targetTouch.clientX
            const endY = targetTouch.clientY

            let width = startWidth + endX - startX
            let height = startHeight + endY - startY

            if(width > pageContainerWidth - startLeft) width = pageContainerWidth - startLeft
            if(height > pageContainerHeight - startTop) height = pageContainerHeight - startTop
            //设定缩放的大小界限
            // if(width > minWidth*5) width = minWidth*5
            // if(height > minHeight*5) height = minHeight*5
            if(width < minWidth) width = minWidth
            if(height < minHeight) height = minHeight

            formData.position.width = width / scale
            formData.position.height = height / scale

            el.style.height = height + "px"
            el.style.width = width + "px"
        }

        const onTouchEnd = e => {
            e.stopPropagation()
            e.preventDefault()
            this.forceUpdate()
            window.removeEventListener("touchmove", onTouchMove, { passive: false })
            window.removeEventListener("touchend", onTouchEnd, { passive: false })
        }

        window.addEventListener("touchmove", onTouchMove, { passive: false })
        window.addEventListener("touchend", onTouchEnd, { passive: false })
    }

  onClickEditorCancel = (e) => {
    e.stopPropagation();
    e.preventDefault();

    let moved = false;

    let startTouch = e.targetTouches[0];
    const { clientX: startX, clientY: startY } = startTouch;

    const onTouchEnd = e => {
      e.preventDefault();
      let endTouch = e.changedTouches[0];
      const { clientX: endX, clientY: endY } = endTouch;

      if ((endX - startX) ** 2 + (endY - startY) ** 2 > 8) moved = true;
      if (!moved) {
        this.props.onDelete && this.props.onDelete();
      }

      window.removeEventListener('touchend', onTouchEnd, { passive: false });
    };

    window.addEventListener('touchend', onTouchEnd, { passive: false });
  };

    render () {
        let containerStyle = null
        let scale = this.props.scale || 1
        const formData = this.props.formData
        const {type}=formData;
        // console.log(formData)
        if(this.state.draging){
            const dragingRect = this.state.dragingRect
            containerStyle = {
                zIndex: 10000,
                position: "fixed",
                top: dragingRect.top + 'px',
                left: dragingRect.left + 'px',
                width: dragingRect.width + 'px',
                height: dragingRect.height + 'px'
            }
        } else {
            const position = formData.position

            containerStyle = {
                top: position.top * scale + 'px',
                left: position.left * scale + 'px',
                width: position.width * scale + 'px',
                height: position.height * scale + 'px'
            }

        }

        const isActive = this.props.isActive
        let containerClasses = []
        containerClasses.push(style.formContainer)
        if(isActive) containerClasses.push(style.active)
        let imageData = this.props.getFormImageData(formData)
        return (
            <div ref={this.formRef} className={containerClasses.join(" ")} style={containerStyle}>
                {
                    imageData && <img src={imageData} className={style.imageBox} alt={imageData}/>
                }
                {
                    isActive && (
                      type==='WRITE_SIGN'?
                        <>
                            <div ref={this.resizeRef} className={style.resizeHandler}>
                                <MyIcon type="icondengbisuofang" className={style.icon}></MyIcon>
                            </div>
                            <div ref={this.deleteRef} className={style.deleteHandler}>
                                <MyIcon type="iconClose" className={style.icon}></MyIcon>
                            </div>
                        </>
                        :
                        <>
                          <div ref={this.deleteRef} className={style.deleteHandler}>
                            <MyIcon type="iconClose" className={style.icon}></MyIcon>
                          </div>
                        </>
                    )
                }
            </div>
        )
    }
}

export { NormalForm }
